package service

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"member_srv/basic/appConfig"
	__ "member_srv/basic/proto"
	"member_srv/handler/models"
	"member_srv/pkg"
	"time"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedMemberServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) GetType(_ context.Context, in *__.GetTypeReq) (*__.GetTypeResp, error) {
	var mt models.MemberTypes
	var lmt []*__.TypesList

	lists, err := mt.GetTypeInfoById(appConfig.DB, in.Id)
	if err != nil {
		return nil, err
	}

	for _, t := range lists {
		list := __.TypesList{
			Id:            int64(t.ID),
			Title:         t.Title,
			Price:         float32(t.Price),
			Duration:      t.Duration,
			PrerogativeId: t.PrerogativeId,
			Status:        t.Status,
		}
		lmt = append(lmt, &list)
	}

	return &__.GetTypeResp{
		List: lmt,
	}, nil
}

func (s *Server) CreateOrder(_ context.Context, in *__.CreateOrderReq) (*__.CreateOrderResp, error) {
	var err error
	var mt models.MemberTypes
	var o models.Orders

	if err = mt.GetTypeById(appConfig.DB, in.MemberTypeId); err != nil {
		return nil, errors.New("获取会员等级信息失败")
	}
	if mt.ID == 0 {
		return nil, errors.New("会员等级不存在！")
	}

	if in.PayType != 1 && in.PayType != 2 {
		return nil, errors.New("支付方式错误！")
	}

	o.UserId = in.UserId
	o.OrderSn = uuid.NewString()
	o.MemberTypeId = in.MemberTypeId
	o.Num = int(in.Num)
	o.Total = mt.Price * float64(in.Num)
	if o.Total > 5000 {
		return nil, errors.New("购买价格异常！")
	}
	o.PayType = in.PayType
	if err = o.CrateOrder(appConfig.DB); err != nil {
		return nil, errors.New("充值订单创建失败！")
	}

	amount := fmt.Sprintf("%.2f", o.Total)
	payUrl, _ := pkg.Alipay(o.OrderSn, amount)

	return &__.CreateOrderResp{
		OrderSn: o.OrderSn,
		PayUrl:  payUrl,
	}, nil
}

func (s *Server) ListOrderByUserId(_ context.Context, in *__.ListOrderByUserIdReq) (*__.ListOrderByUserIdResp, error) {

	var or models.Orders
	var lor []*__.OrderList

	lists, err := or.ListOrders(appConfig.DB, in.UserId)
	if err != nil {
		return nil, err
	}

	for _, t := range lists {
		list := __.OrderList{
			Id:           int64(t.ID),
			UserId:       t.UserId,
			OrderSn:      t.OrderSn,
			MemberTypeId: t.MemberTypeId,
			Total:        float32(t.Total),
			PayType:      t.PayType,
			Status:       t.Status,
			CreatedAt:    t.CreatedAt.Format(time.RFC3339),
		}
		lor = append(lor, &list)
	}

	return &__.ListOrderByUserIdResp{
		List: lor,
	}, nil
}

func (s *Server) UpdateOrder(_ context.Context, in *__.UpdateMemberReq) (*__.UpdateMemberResp, error) {
	var err error
	var u models.User
	var o models.Orders

	if err = o.UpdateStatus(appConfig.DB, in.OrderSn, in.OrderStatus); err != nil {
		return nil, errors.New("订单状态更新失败")
	}

	if err = appConfig.DB.Model(&u).Where("id=?", o.UserId).
		Update("member_status", in.MemberStatus).Error; err != nil {
		return nil, errors.New("用户会员等级更新失败")
	}

	if err = appConfig.DB.Model(&u).Where("id=?", o.UserId).
		Update("member_expired_at", in.MemberExpiredAt).Error; err != nil {
		return nil, errors.New("服务到期时间更新失败")
	}

	return &__.UpdateMemberResp{
		OrderSn: in.OrderSn,
		Msg:     "订单状态及用户特权信息更新成功",
	}, nil
}
